#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Time    : 2020/12/3 16:27

import random
import time
from collections import OrderedDict

import hashlib

from common.utils import Utils


class UtilsParam:

    @staticmethod
    def third_ad_param(data_param, sign_key="bj7ttACLb3E$bCu9lyB8ilbA6f%094vl"):
        """
        广告SDK回调加密方法
        :param data_param: 未加密入参
        :param sign_key: 秘钥
        :return:
        """
        data_param['sign_key'] = sign_key
        data_param['timestamp'] = Utils.get_current_timestamp('s')
        if type(data_param) == dict:
            sort_key = sorted(data_param, key=lambda x: x, reverse=False)
            sort_key_data = ''
            for key in sort_key:
                sort_key_data = sort_key_data + str(key) + str(data_param[key])

            sha = hashlib.sha1(sort_key_data.encode('utf-8'))
            encrypts = sha.hexdigest()

            data_param['sign'] = encrypts
            data_param.pop('sign_key')

            return data_param
        else:
            raise TypeError("类型错误，请初入dict类型")

    @staticmethod
    def third_game_param(data_param):
        """
        充值游戏加密方法
        :param data_param: 未加密入参
        :return:
        """
        sign_key = "de2dc60b1ca0457d9dabe06537cf37a7"
        if type(data_param) == dict:
            sort_key = sorted(data_param, key=lambda x: x, reverse=False)
            sort_key_data = ''
            for key in sort_key:
                sort_key_data = sort_key_data + str(key) + '=' + str(data_param[key]) + '&'

            sort_key_data += 'key=' + sign_key
            sha = hashlib.md5(sort_key_data.encode('utf-8'))
            encrypts = sha.hexdigest()

            data_param['sign'] = encrypts.upper()
            print(data_param)

            return data_param
        else:
            raise TypeError("类型错误，请输入dict类型")

    @staticmethod
    def third_ad_param_novel(data_param):
        """
        小满小说广告回调加密
        :param data_param: 未加密入参
        :return:
        """
        sign_key = "c3d0cd2c731a"
        if type(data_param) == dict:
            sort_key = sorted(data_param, key=lambda x: x, reverse=False)
            print('sort_key->', sort_key)
            sort_key_data = ''
            for key in sort_key:
                sort_key_data = sort_key_data + str(key) + '=' + str(data_param[key]) + '&'

            sort_key_data += 'key=' + sign_key
            print('sort_key_data->', sort_key_data)
            sha = hashlib.md5(sort_key_data.encode('utf-8'))
            encrypts = sha.hexdigest()

            data_param['sign'] = str(encrypts).upper()

            return data_param
        else:
            raise TypeError("类型错误，请初入dict类型")

    @staticmethod
    def third_ad_param_zuo_tang(data_param):
        """
        广告左唐加密方法
        :param data_param:
        :return:
        """
        key = "8d4a216daf3c808a33e788059bf0c43d"
        trans_id = data_param['trans_id']
        str_sign = key + ':' + trans_id
        print(str_sign)
        sha = hashlib.md5(str_sign.encode('utf-8'))
        sign = sha.hexdigest()
        data_param['sign'] = str(sign).lower()
        return data_param

    @staticmethod
    def third_yg_param(data_param, sign_key="bj7ttACLb3E$bCu9lyB8ilbA6f%094vl"):
        """
        阳光三方接口请求加密
        :param data_param: 未加密入参
        :param sign_key: 秘钥
        :return:
        """
        data_param['sign_key'] = sign_key
        if type(data_param) == dict:
            sort_key = sorted(data_param, key=lambda x: x, reverse=False)
            sort_key_data = ''
            for key in sort_key:
                if data_param[key] != '' and key != 'is_test':
                    sort_key_data = sort_key_data + str(key) + str(data_param[key])

            sha = hashlib.md5(sort_key_data.encode('utf-8'))
            encrypts = sha.hexdigest()

            data_param['sign'] = str(encrypts).upper()
            data_param.pop('sign_key')

            return data_param
        else:
            raise TypeError("类型错误，请初入dict类型")

    @staticmethod
    def call_param(data_param):
        """
        积分打电话请求加密
        :param data_param: 未加密入参
        :return:
        """
        if type(data_param) == dict:
            sort_key = sorted(data_param, key=lambda x: x, reverse=False)
            sort_key_data = ''
            for key in sort_key:
                if data_param[key] != '' and key != 'is_test':
                    sort_key_data = sort_key_data + str(key) + str(data_param[key])
            t = 'sbdcallback1.0' + str(sort_key_data) + 'sbdcallback1.0'
            sha = hashlib.md5(t.encode('utf-8'))
            encrypts = sha.hexdigest()

            data_param['sign'] = str(encrypts).lower()

            return data_param
        else:
            raise TypeError("类型错误，请初入dict类型")

    @staticmethod
    def vending_machine_param():
        """
        自动售货机参数加密
        :param data_param: 未加密入参
        :return:
        """
        app_id = "8cJvbyS0CCIm"
        app_sign_key = "cLBl79CBQMut1st2sDngmCEcTn47S0fu"
        nonce_str = str(random.randint(0, 99999999)).rjust(8, "0") + str(random.randint(0, 999999)).rjust(6, "0")
        timestamp_str = str(int(time.time() * 1000))
        sign_str = "appId=" + app_id + "&appSignKey=" + app_sign_key + "&nonce=" + nonce_str + "&timestamp=" + timestamp_str
        sha = hashlib.sha1(sign_str.encode('utf-8'))
        encrypts = sha.hexdigest()

        param = dict()
        param['Content-Type'] = 'application/json;charset=UTF8'
        param['appId'] = app_id
        param['nonce'] = nonce_str
        param['timestamp'] = timestamp_str
        param['sign'] = encrypts

        return param

    @staticmethod
    def sort_param(data_param):
        """
        :param data_param:
        :return:order_dict，order_list
        """
        # 最终需要的参数列表
        order_list = []
        # 暂存用dict
        order_dict = OrderedDict()

        # 遍历参数
        for key, value in data_param.items():

            # 可能存在相同的key所以用list存放
            order_dict[key] = []

            if type(value) == list:
                for item in value:
                    return_dict = UtilsParam.sort_param(item)
                    for list_key, list_value in return_dict[0].items():
                        order_list.append(str(list_key) + '=' + str(*list_value))

            elif type(value) == dict:
                return_dict = UtilsParam.sort_param(value)
                for dict_key, dict_value in return_dict[0].items():
                    order_list.append(str(dict_key) + '=' + str(dict_value))
            else:
                if value == '':
                    # 跳过为空参数
                    pass
                else:
                    order_list.append(str(key) + '=' + str(value))
                    order_dict[key].append(value)

        return order_dict, order_list

    @staticmethod
    def param_encrypt_df(data_param, third_type):
        """
        笛风加密算法
        :param: data_param：传入DICT入参
        :param: third_type: 类型，酒店或者机票hotel,air
        :return:  返回加密请求参数，可直接使用参数请求（类型dict）
        """
        if third_type == 'hotel':
            api_key = 'hoteltest'
            secret_key = 'aaaaaaaa'
        elif third_type == 'air':
            # api_key = '233963_DomesticFlightNew'
            # secret_key = 'LwBwolJwjqA9tEnoaU6P'
            api_key = 'dflighttest'
            secret_key = 'aaaaaaaa'
        elif third_type == 'air_old':
            # api_key = '233963_DomesticFlight'
            # secret_key = 'QKBvoKKtfOfNkEQQFNyI'
            api_key = 'jdtest'
            secret_key = 'aaaaaaaa'
        else:
            raise ValueError("Type错误！")

        if type(data_param) == dict:
            timestamp = Utils.get_current_datetime()
            data_param['apiKey'] = api_key
            data_param['timestamp'] = timestamp

            sort_param_list = UtilsParam.sort_param(data_param)[1]

            # 转换成用&连接的字符串
            sort_param_list = sorted(sort_param_list, key=lambda x: x, reverse=False)

            str_data = ''
            for item in sort_param_list:
                str_data += item + '&'

            # md5
            # sign = Utils.text_to_md5(secret_key + '&' + str_data + secret_key).upper()
            sort_key_data = secret_key + '&' + str_data + secret_key
            sha = hashlib.md5(sort_key_data.encode('utf-8'))
            sign = sha.hexdigest().upper()

            # 移除项
            data_param.pop('apiKey')
            data_param.pop('timestamp')

            # 拼接最终请求参数
            secret_param = dict()
            secret_param['apiKey'] = api_key
            secret_param['sign'] = sign
            secret_param['timestamp'] = timestamp
            secret_param['data'] = data_param

            return secret_param
        else:
            raise ValueError("请传入dict类型")


if __name__ == '__main__':
    a = UtilsParam.vending_machine_param()
    b = {'a': 123}
    print({**a, **b})
